package com.kaifamiao.base.Demo20210918;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * @author lucien-ma
 * @date 2021/9/18
 * @apiNote
 */
public class Demo02 {

    public static void main(String[] args) {
        int dec = input();
        int[] binary = negativeToBinary(dec);
        show(binary);
    }

    /**
     * 求出一个负整数的 补码
     * @param dec
     */
    public static int[] negativeToBinary(int dec) {
        // 先求出源码
        int[] code = getSourceCode(dec);
        // 求反码
        for (int i = 1; i < code.length; i++) {
            if (code[i] == 1) {
                code[i] = 0;
            } else {
                code[i] = 1;
            }
        }
        // 反码加一
        for (int i = code.length - 1; i > 0; i--) {
            if (code[i] == 0) {
                code[i] = 1;
                break;
            }else if (code[i] == 1) {
                code[i] = 0;
            }
        }
        return code;
    }

    /**
     * 求出源码
     * @param dec
     * @return
     */
    private static int[] getSourceCode(int dec) {
        int[] sourceCode = new int[32];
        Arrays.fill(sourceCode, 0);
        // 符号位
        sourceCode[0] = 1;
        // 传进来的十进制数
        int decTemp = Math.abs(dec);
        // 转换的进制
        int divisor = 2;
        // 往数组中放入的位置
        int p = sourceCode.length - 1;
        do {
            // 余数
            int remainder = decTemp % divisor;
            // 解析余数
            sourceCode[p--] = remainder;

            // 计算商
            decTemp = decTemp / divisor;
        } while (decTemp != 0);
        return sourceCode;
    }

    /**
     * 展示二进制数
     */
    public static void show(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (i != 0 && i % 4 == 0) {
                System.out.print(" ");
            }
            System.out.print(arr[i]);
        }
    }

    public static int input() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个十进制负整数：");
        return scanner.nextInt();
    }

}
